package com.matt.controller.web.cookbook;


import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.utils.DateUtil;
import com.matt.domain.cookbook.Recipe;
import com.matt.domain.cookbook.RecipeConfig;
import com.matt.domain.cookbook.RecipeFood;
import com.matt.domain.cookbook.RecipeShow;
import com.matt.foundation.ext.aliyun.OSSProcessService;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.CookbookUtils;
import com.matt.foundation.utils.ExcelOperateUtil;
import com.matt.foundation.utils.PoiUtils;
import com.matt.foundation.vo.ChildrenListVo;
import com.matt.service.ChildrenService;
import com.matt.service.WxPushService;
import com.matt.service.cookbook.RecipeConfigService;
import com.matt.service.cookbook.RecipeFoodService;
import com.matt.service.cookbook.RecipeService;
import com.matt.service.cookbook.RecipeShowService;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.assertj.core.util.Arrays;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

import static com.matt.foundation.constant.RequestConstant.TICKET;

;

/**
 *
 * 功能描述：食谱
 *
 */
@Controller
@RequestMapping("/web/recipe")
public class WebCookbookController  {

	@Autowired
	private RecipeService recipeService;

	@Autowired
	private RecipeFoodService recipeFoodService;

	@Autowired
	private RecipeShowService recipeShowService;

	@Autowired
	private RecipeConfigService recipeConfigService;

	@Autowired
	private ChildrenService childrenService;

	@Autowired
	private WxPushService wxPushService;

	@Autowired
	private MemVerificationCache cache;

	@Autowired
	private SsoCallService ssoCallService;

	@Autowired
	private OSSProcessService ossProcessService;

	@Value("${aliyun.oss.fileServerPrefix}")
	private String IMG_SERVICE_PREFIX;


	@Value("${img.service.base.url}")
	private String imgServiceBaseURL;


	/**复制食谱保存校验**/
	@ApiOperation(value = "复制食谱保存校验",httpMethod = "POST")
	@RequestMapping(value = "/checkCopyRecipe")
	@ResponseBody
	public StatusResponse checkCopyRecipe(@RequestHeader(TICKET) String ticket, String copyToStartTime , String copyToEndTime){

		String areaId = cache.getAreaId(ticket);

		List<Recipe> recipeList = this.recipeService.selectList(copyToStartTime,copyToEndTime,areaId);

		int size = recipeList.size();

		if(size != 0){
			return StatusResponse.error(ErrorCode.RECIPE_EXIST, "");
		}

		return StatusResponse.success();
	}


	/**
	 * 复制食谱保存
	 *
	 * @return
	 */

	@ApiOperation(value = "复制食谱保存",httpMethod = "POST")
	@RequestMapping(value = "/addCopyRecipe")
	@ResponseBody
	public StatusResponse addCopyRecipe(@RequestHeader(TICKET) String ticket,
										String copyFromStartTime,String copyFromEndTime ,String copyToStartTime ,String copyToEndTime ,String addFlag ){

		String areaId = cache.getAreaId(ticket);
		List<String> timeArr = CookbookUtils.getDayConvert(copyToStartTime,7);

		// 复制数据
		List<Recipe> recipeList_from = this.recipeService.selectList(copyFromStartTime,copyFromEndTime,areaId);/*被复制周期的食谱*/
		List<Recipe> copyList = new ArrayList<Recipe>();
		for(int i=0;i<recipeList_from.size();i++){
			Recipe r = recipeList_from.get(i);
			String  rTime = CookbookUtils.dateToStr(r.getRecipeDate(),"yyyy-MM-dd");//获取要复制的食谱 时间
			String  rTimeName = CookbookUtils.getWeekOfDate(rTime);//获取 食谱是周几

			for(int j=0;j<timeArr.size();j++){
				String timeString= timeArr.get(j);//获取复制到的食谱时间
				String weekName= CookbookUtils.getWeekOfDate(timeString);//获取复制到的食谱是周几
				if(rTimeName.equals(weekName)){
					Recipe newR = new Recipe();
					newR.setAreaId(r.getAreaId());
					newR.setFoodId(r.getFoodId());
					newR.setRecipeTypeId(r.getRecipeTypeId());
					newR.setRecipeTypeName(r.getRecipeTypeName());
					newR.setRecipeDate(DateUtil.parseToPattern(timeString, "yyyy-MM-dd"));
					copyList.add(newR);
					break;
				}
			}
		}

		//删除老记录
		List<Recipe> recipeList = this.recipeService.selectList(copyToStartTime, copyToEndTime, areaId);
		if(recipeList != null && recipeList.size() > 0) {
			recipeService.deleteAll(recipeList);
		}

		//插入数据
		recipeService.insertRecipeByRecipeList(copyList);


		//创建新的json，YBB老代码，似乎没啥用处
		List<Recipe> recipeList_copy = this.recipeService.selectList(copyToStartTime, copyToEndTime, areaId);

		for(Recipe p : recipeList_copy){
			recipeShowService.deleteRecipeShowByTimeAndAreaId(CookbookUtils.dateToStr(p.getRecipeDate(), "yyyy-MM-dd") , areaId);

			String recipeShowJson = recipeShowService.createRecipeShowJson(CookbookUtils.dateToStr(p.getRecipeDate(), "yyyy-MM-dd"), areaId);
			recipeShowService.createRecipeShow(areaId, p.getRecipeDate(), recipeShowJson);
		}

		return StatusResponse.success();
	}

	/**
	 * 园长查看  健康食谱
	 * @param
	 * @return
	 */

	@ApiOperation(value = "园长查看  健康食谱",httpMethod = "POST")
	@RequestMapping(value = "/selectRecipeListBySchool" ,produces = "application/json; charset=utf-8")
	@ResponseBody
	public StatusResponse selectRecipeListBySchool(@RequestHeader(TICKET) String ticket,
												 String startDate, String endDate){

		String areaId = cache.getAreaId(ticket);

        List<Map<String, Object>> list = getAWeekRecipeList(startDate, areaId);

        Map<String, Object> model = new HashMap<>();
		model.put("list", list);
		model.put("pathRoot", imgServiceBaseURL + "/teach/static");

		return StatusResponse.success(model);
	}

    private List<Map<String, Object>> getAWeekRecipeList(String startDate, String areaId) {
        List<Map<String, Object>> list = new ArrayList<>();
        //startDate="2015-07-18";  //页面传入的开始日期
        List<String> timeArr = CookbookUtils.getDayConvert(startDate, 7);

        List<String> weekListTab = new ArrayList<>();
        for (int i = 0; i < timeArr.size(); i++) {
            String timeString = timeArr.get(i);
            String weekName = CookbookUtils.getWeekOfDate(timeString);
            weekListTab.add(weekName + "/" + timeString.substring(5));
        }

        List<RecipeConfig> recipeTypeList = recipeConfigService.selectRecipeTypeByAreaId(areaId);/**查询学校的餐次信息**/

        for (int i = 0; i < recipeTypeList.size(); i++) {
            List<List<Map<String, Object>>> resultList = new ArrayList<>();

            Map<String, Object> resultMap = new HashMap<>();
            String recipeTypeId = recipeTypeList.get(i).getValue();
            String recipeTypeName = recipeTypeList.get(i).getName();

            for (int j = 0; j < timeArr.size(); j++) {

                String time = timeArr.get(j);
                Map<String, Object> params = new HashMap<String, Object>();

                params.put("recipeTypeId", recipeTypeId);
                params.put("areaId", areaId);
                params.put("startTime", time);
                params.put("endTime", time);
                List<Map<String, Object>> recipeMapList = recipeService.selectRecipeFoodByTime(params);
                resultList.add(recipeMapList);
            }

            resultMap.put("recipeTypeName", recipeTypeName);
            resultMap.put("recipeTypeId", recipeTypeId);
            resultMap.put("recipeDayFoods", resultList);

            list.add(resultMap);
        }
        return list;
    }

    /**
	 * 配置食谱
	 * @param
	 * @return
	 */
	@ApiOperation(value = "配置食谱",httpMethod = "POST")
	@RequestMapping(value = "/addRecipeFood" )
	@ResponseBody
	public StatusResponse addRecipeFood(@RequestHeader(TICKET) String ticket,
										String recipeDate,String recipeFoodStr ){
		String areaId = cache.getAreaId(ticket);

		Date date = DateUtil.parseToPattern(recipeDate, "yyyy-MM-dd");

		List<Recipe> recipeFoodList = new ArrayList<Recipe>();

		String [] arry = recipeFoodStr.split("\\|");

		for(String recipeFoodString :arry){
			if(recipeFoodString !=""){
				String []  arrRecipeFood = recipeFoodString.split("-");
				String recipeTypeValue = arrRecipeFood[0].trim();
				String recipeTypeName = arrRecipeFood[1].trim();
				String foodId = arrRecipeFood[2].trim();

				Map<String, Object> filter = new HashMap<String, Object>();
				filter.put("areaId", areaId);
				filter.put("foodId", Long.valueOf(foodId));
				filter.put("recipeTypeId",Long.valueOf(recipeTypeValue ));
				filter.put("startTime", recipeDate);
				filter.put("endTime", recipeDate);

				List<Recipe> isExit = recipeService.selectRecipeListByCondition(filter);

				if(isExit.size() ==0){
					Recipe recipe = new Recipe();
					recipe.setFoodId(Long.valueOf(foodId));
					recipe.setRecipeDate(date);
					recipe.setRecipeTypeId(Long.valueOf(recipeTypeValue));
					recipe.setRecipeTypeName(recipeTypeName);
					recipe.setAreaId(areaId);

					recipeFoodList.add(recipe);
				}
			}
		}

		if(recipeFoodList.size() !=0){
			recipeService.insertRecipeByRecipeList(recipeFoodList);
		}

		recipeShowService.deleteRecipeShowByTimeAndAreaId(recipeDate, areaId);

		String recipeShowJson = recipeShowService.createRecipeShowJson(recipeDate, areaId);

		RecipeShow show = recipeShowService.createRecipeShow(areaId, date, recipeShowJson);

 		return StatusResponse.success(show);
	}

	@SuppressWarnings("rawtypes")



	private List fillFoodTypeList(List<RecipeConfig> foodTypeList, String areaId){


		Map<String, Object> filter = new HashMap<String, Object>();
		filter.put("areaId", areaId);
		List<RecipeFood> foodList = recipeFoodService.selectRecipeFoodListByCondition(filter);

		Map<Integer, List<RecipeFood>> cache = new HashMap();
		for(RecipeFood food : foodList){
			List<RecipeFood> list =  cache.get(food.getType());
			if(list == null){
				list = new ArrayList<>();
				cache.put(food.getType(), list);
			}
			list.add(food);
		}

		List<Map> list = new ArrayList<Map>();
		for(int i=0;i<foodTypeList.size();i++){
			RecipeConfig config = foodTypeList.get(i);
			Integer type = Integer.valueOf(config.getValue());
			String name = config.getName();

			List<RecipeFood> typeFoodList = cache.get(type);

			Map<String, Object> resultMap = new HashMap<>();

			resultMap.put("type", type);
			resultMap.put("name", name);
			resultMap.put("sort", config.getSortId());
			resultMap.put("foods", typeFoodList);

			list.add(resultMap);
		}
		return list;
	}

//	/**
//	 * 添加食物
//	 * @param ticket
//	 * @param timeStr
//	 * @param recipeName
//	 * @param recipeId
//	 * @return
//	 */
//	@ApiOperation(value = "添加食物候选列表",httpMethod = "POST")
//	@RequestMapping(value = "/prepare_add_food")
//	@ResponseBody
//	public StatusResponse addFood(@RequestHeader(TICKET) String ticket  ){
//		String areaId = cache.getAreaId(ticket);
//
//		List<RecipeConfig> recipeTypeList = recipeConfigService.selectRecipeTypeByAreaId(areaId);/**查询学校的餐次信息**/
//		List<RecipeConfig> foodTypeList = recipeConfigService.selectFoodType();
//
//
//		List list = fillFoodTypeList(foodTypeList, areaId);
//
//		Map result = new HashMap();
//		result.put("list", list);
//		result.put("recipeTypeList", recipeTypeList);
//		result.put("pathRoot", imgServiceBaseURL); //服务器上图片的跟路径
//
//		return StatusResponse.success(result);
//	}


	/**
	 * 跳转配置食谱页面
	 * @param ticket
	 * @return
	 */
	@ApiOperation(value = "配置食谱页数据, 餐次列表和食物类型列表",httpMethod = "POST")
	@RequestMapping(value = "/recipe_and_food_types")
	@ResponseBody
	public StatusResponse configFood(@RequestHeader(TICKET) String ticket){

		String areaId = cache.getAreaId(ticket);

		List<RecipeConfig> recipeTypeList = recipeConfigService.selectRecipeTypeByAreaId(areaId);/**查询学校的餐次信息**/

		List<RecipeConfig> foodTypeList = recipeConfigService.selectFoodType();

		List list = fillFoodTypeList(foodTypeList, areaId);

		Map result = new HashMap();

		result.put("foodTypeList", list);
		result.put("recipeTypeList", recipeTypeList);
		result.put("listCount", recipeTypeList.size());
		result.put("pathRoot", imgServiceBaseURL + "/teach/static"); //服务器上图片的跟路径
//		result.put("foodTypeList", foodTypeList);

		return StatusResponse.success(result);
	}

	/**新增餐次**/
	@ApiOperation(value = "新增餐次",httpMethod = "POST")
	@RequestMapping(value = "/addRecipeType")
	@ResponseBody
	public StatusResponse addRecipeType(@RequestHeader(TICKET) String ticket, String recipeName){
		String areaId = cache.getAreaId(ticket);

		RecipeConfig dictionary = recipeConfigService.selectConfigNameIsExit(areaId, "recipe_type", recipeName);
		if(dictionary != null){
			return  StatusResponse.error(ErrorCode.RECIPE_EXIST, "餐次名字已存在!");
		}

//		List<RecipeConfig> recipeTypeList = recipeConfigService.selectRecipeTypeByAreaId(areaId);/**查询学校的餐次信息**/

		return StatusResponse.success(recipeConfigService.insertRecipeType(areaId, recipeName));
	}



	/**新增食物名字**/
	@ApiOperation(value = "增加食物名字",httpMethod = "POST")
	@RequestMapping(value = "/addFoodName")
	@ResponseBody
	public StatusResponse addFoodName(@RequestHeader(TICKET) String ticket,
							  String foodTypeId, String addFoodName, String imageId){
//		String imagerPath="/recipe/"+imageId+".png";
		String imagerPath = "/recipe/" + imageId + ".png";

		String areaId = cache.getAreaId(ticket);

		RecipeFood isExitFood = recipeFoodService.selectRecipeFoodByName(addFoodName, areaId);

		if(isExitFood !=null){
			return  StatusResponse.error(ErrorCode.RECIPE_EXIST, "食物名字已存在!");
		}

		RecipeFood food = recipeFoodService.createRecipeFood(addFoodName.trim(), areaId, Integer.parseInt(foodTypeId), imagerPath);

		return StatusResponse.success(food);
	}

	/**修改食物名字**/
	@ApiOperation(value = "修改食物名字",httpMethod = "POST")
	@RequestMapping(value = "/modifyFoodName")
	@ResponseBody
	public StatusResponse modifyFoodName(@RequestHeader(TICKET) String ticket, String modifyFoodId, String modifyFoodName, Integer imageId){

		String areaId = cache.getAreaId(ticket);

		RecipeFood food = recipeFoodService.selectByAreaIdAndId(areaId, Long.parseLong(modifyFoodId));

		if(food == null){
			return StatusResponse.error(ErrorCode.RECIPE_NOT_EXIST, "没有找到食物");
		}

		if(!food.getName().equals(modifyFoodName)){
			RecipeFood isExitFood = recipeFoodService.selectRecipeFoodByName(modifyFoodName, areaId);
			if(isExitFood != null){
				return StatusResponse.error(ErrorCode.RECIPE_EXIST, "已经存在对应名字的食物");
			}
		}

		food.setName(modifyFoodName);

		if(imageId != null && imageId != -1){
			String imagerPath = "/recipe/" + imageId + ".png";
			food.setPhoto(imagerPath);
		}

		food = recipeFoodService.updateRecipeFood( food );

		return StatusResponse.success(food);
	}

	/**修改餐次名字**/
	@ApiOperation(value = "修改餐次名字",httpMethod = "POST")
	@RequestMapping(value = "/modifyRecipeName")
	@ResponseBody
	public StatusResponse modifyRecipeName(@RequestHeader(TICKET) String ticket, String recipeTypeName,String recipeTypeValue, HttpServletRequest request){

		String areaId = cache.getAreaId(ticket);

		RecipeConfig config = recipeConfigService.selectConfigNameIsExit(areaId, "recipe_type", recipeTypeName);
		if(config !=null){
			return StatusResponse.error(ErrorCode.RECIPE_EXIST, "餐次名字已存在!");
		}

		config.setValue(recipeTypeValue);
		config.setName(recipeTypeName);

		recipeConfigService.updateConfig(config);

		return StatusResponse.success(config);
	}


	/**
	 * 删除餐次
	 * @param recipeId  字典表中餐次recipeId
	 */
	@ApiOperation(value = "删除餐次",httpMethod = "POST")
	@RequestMapping(value = "/deleteRecipe")
	@ResponseBody
	public StatusResponse deleteRecipe(@RequestHeader(TICKET) String ticket, String recipeId){

		String areaId = cache.getAreaId(ticket);

		String nowTime = CookbookUtils.getNowTime(null);

		RecipeConfig config = recipeConfigService.deleteConfigByAreaIdAndTypeAndValue(areaId,  Long.valueOf(recipeId));
		recipeService.deleteRecipeBySchoolAndTime(areaId, nowTime, Long.valueOf(config.getValue()));

		return StatusResponse.success();
	}


	/**
	 * 更改餐次排序
	 *
	 */
	@ApiOperation(value = "更改餐次顺序",httpMethod = "POST")
	@RequestMapping(value = "/updateRecipeSort")
	@ResponseBody
	public StatusResponse updateRecipeSort(@RequestHeader(TICKET) String ticket,String recipeId, String type){
		String areaId = cache.getAreaId(ticket);

		if("up".endsWith(type)){
			recipeConfigService.upRecipeTypeSort(areaId, recipeId);
		}

		if("down".equals(type)){
			recipeConfigService.downRecipeTypeSort(areaId, recipeId);
		}
		return StatusResponse.success();
	}


	/**
	 *食谱配置 删除食物
	 *
	 */
	@ApiOperation(value = "删除食物",httpMethod = "POST")
	@RequestMapping(value = "/deleteFood")
	@ResponseBody
	public StatusResponse deleteFood(@RequestHeader(TICKET) String ticket, String id){

		String areaId = cache.getAreaId(ticket);

		RecipeFood recipeFood = recipeFoodService.selectByAreaIdAndId(areaId, Long.valueOf(id));
		if(recipeFood == null){
			return StatusResponse.error(ErrorCode.RECIPE_NOT_EXIST, "没有找到食物");
		}

		return StatusResponse.success(recipeFoodService.deleteRecipeFood(recipeFood));
	}


	/**
	 * 删除食谱某天的食物
	 * @param ticket
	 * @param id
	 * @return
	 */
	@ApiOperation(value = "删除食谱某天的食物",httpMethod = "POST")
	@RequestMapping(value = "/deleteRecipeFood")
	@ResponseBody
	public StatusResponse deleteRecipeFood(@RequestHeader(TICKET) String ticket, String id){

		String areaId = cache.getAreaId(ticket);

		Recipe deleteRecipe = recipeService.findByIdAndAreaId(Long.parseLong(id), areaId);

		if(deleteRecipe == null){
			return StatusResponse.error(ErrorCode.RECIPE_NOT_EXIST, "没有找到食谱");
		}

		Date date = deleteRecipe.getRecipeDate();
		String deleteRecipeTime = CookbookUtils.dateToStr(date, CookbookUtils.DEFINE_YYYY_MM_DD) ;
		String nowTimeStr = CookbookUtils.dateToStr(new Date(), CookbookUtils.DEFINE_YYYY_MM_DD) ;

		if(deleteRecipeTime.compareTo(nowTimeStr) < 0){
			return  StatusResponse.error(ErrorCode.NURSERY_DATE_OUT_LIMIT, "不能修改过去的食谱!");
		}

		recipeService.deleteById(Long.parseLong(id));

		recipeShowService.deleteRecipeShowByTimeAndAreaId(deleteRecipeTime, areaId);

		String recipeShowJson = recipeShowService.createRecipeShowJson(deleteRecipeTime, areaId);
		if(StringUtils.isNotEmpty(recipeShowJson)){
			recipeShowService.createRecipeShow(areaId, date, recipeShowJson);
		}
		return StatusResponse.success();
	}


	/**发布餐次**/
	@ApiOperation(value = "发布食谱(推送食谱，无状态改变)",httpMethod = "POST")
	@RequestMapping(value = "/publishRecipe")
	@ResponseBody
	public StatusResponse publishRecipe(@RequestHeader(TICKET) String ticket,
										String startDate,String endDate){
		StaffDTO staffBaseDTO = cache.getStaff(ticket);
		String areaId = staffBaseDTO.getAreaId();

		List<Map<String, String>> weekList = CookbookUtils.getWeekList(2, 1);

		String currWeekStartDate = null; //weekList.get(1).get("start");
		String nextWeekStartDate = null; //weekList.get(2).get("start");
		for(int i = 0; i < weekList.size(); i++){
			Map<String, String> m = weekList.get(i);
			if(m.containsKey("curr")){
				currWeekStartDate = m.get("start");
			}else if(nextWeekStartDate == null && currWeekStartDate!= null){
				nextWeekStartDate = m.get("start");
				break;
			}
		}

		boolean flag = false;
		if(startDate.equals(currWeekStartDate)){
			flag = true;
		}

		if(startDate.equals(nextWeekStartDate)){
			flag = true;
		}

		if(flag){
			//推送  每天仅一次
			RecipeConfig config = recipeConfigService.selectConfigByAreaIdAndTypeAndName(areaId, "RECIPE_PUSH", startDate);
			if(config != null){
				return  StatusResponse.error(ErrorCode.RECIPE_ALREADY_PUSHED, "这周食谱已经推送过了哦！");
			}

			//TODO: 这里需要改成批量推送，一个个推太吃资源了
			int count = 0;
			List<ChildrenListVo> children = childrenService.getHasChildrenByArea(areaId);
			for (ChildrenListVo c : children){
				if(c.getStatus() != 1){
					continue;
				}

				wxPushService.pushRecipeReport(areaId, c.getId(), c.getName(), staffBaseDTO.getRealName(), startDate, endDate );
				count += 1;
			}

			//保存
			if(children.size() > 0) {
				config = new RecipeConfig();
				config.setName(startDate);
				config.setType("RECIPE_PUSH");
				config.setValue("" + children.size());
				config.setAreaId(areaId);
				config.setMemo("推送记录：" + staffBaseDTO.getRealName());
				recipeConfigService.updateConfig(config);
			}
			return StatusResponse.success(count);
		}else {
			return StatusResponse.error(ErrorCode.NURSERY_DATE_OUT_LIMIT, "仅当周和次周能推送发布!");
		}
	}

	/**加载基础食物的数据**/
	@ApiOperation(value = "加载基础食物的数据",httpMethod = "POST")
	@RequestMapping(value = "/load_base_food_config")
	@ResponseBody
	public StatusResponse loadBaseFoodList(@RequestHeader(TICKET) String ticket){
		String areaId = cache.getAreaId(ticket);
		recipeFoodService.insertRecipeFoodByTemplate(areaId);
		return StatusResponse.success(configFood(ticket));
	}

	/**发布餐次**/
	@ApiOperation(value = "导入模板",httpMethod = "POST")
	@RequestMapping(value = "/import_recipe_food_from_template")
	@ResponseBody
	public StatusResponse importFoodFromTemplate(@RequestHeader(TICKET) String ticket,
												 @RequestParam MultipartFile file) throws Exception{
		String areaId = cache.getAreaId(ticket);

		InputStream input = file.getInputStream();
		String fileName = file.getOriginalFilename();
		Workbook book = ExcelOperateUtil.getWorkbook(input,fileName);
		Sheet sheet = book.getSheetAt(0);

		List<Recipe> recipeList = new ArrayList<>();
		List<DateTime> recipeDateList = new ArrayList<>();

		Row row1 = sheet.getRow(1);
		for (int i = row1.getFirstCellNum() + 1; i < row1.getLastCellNum(); i++) {

			Cell cell = row1.getCell(i);
			String cellValue = cell.getStringCellValue();
			String dateString = cellValue.split("/")[1];
			int year = DateTime.now().getYear();
			DateTime recipeDateTime = DateTime.parse(year + "-" + dateString);
			if(recipeDateTime.getMonthOfYear() < DateTime.now().getMonthOfYear()){
				recipeDateTime = recipeDateTime.plusYears(1);
			}
			Date recipeDate = recipeDateTime.toDate();
			recipeDateList.add(recipeDateTime);

			//日期行下所有行
			for (int j = row1.getRowNum() + 1; j <= sheet.getLastRowNum(); j++) {
				Row rowJ = sheet.getRow(j);
				//和日期列同步
				for (int k = i; k <= i; k++) {
					Cell rowJCellK = rowJ.getCell(k);
					String rowJCellKValue = rowJCellK.getStringCellValue();
					if(StringUtils.contains(rowJCellKValue,"，"))
						rowJCellKValue = rowJCellKValue.replace("，",",");

					String[] foods = rowJCellKValue.split(",");
					if (Arrays.isNullOrEmpty(foods)) continue;

					for (int m = 0; m < foods.length; m++) {
						String _foodName = foods[m];
						if (StringUtils.isBlank(_foodName)) continue;

                        try {

                            String recipeTypeName = rowJ.getCell(rowJ.getFirstCellNum()).getStringCellValue();
                            String foodName = _foodName.replaceAll("\\s*", "");
                            RecipeFood recipeFood = recipeFoodService.selectRecipeFoodByAreaIdAndName(areaId, foodName);
                            RecipeConfig recipeConfig = recipeConfigService.selectRecipeConfigByAreaIdAndNameAndType(areaId, recipeTypeName, RecipeConfigService.RECIPE_TYPE_KEY);
                            if (Objects.isNull(recipeConfig)) {
                                recipeConfig = recipeConfigService.insertRecipeType(areaId, recipeTypeName);
                            }

                            if (Objects.isNull(recipeFood)) {
                                recipeFood = new RecipeFood();
                                recipeFood.setAreaId(areaId);
                                recipeFood.setName(foodName);
                                recipeFood.setPhoto("/recipe/2.png");

                                //static value
                                recipeFood.setType(1);
                                recipeFood.setTypeName("主食");

								recipeFood = recipeFoodService.insertRecipeFood(recipeFood);
                            }

//							String areaId = (String) filter.get("areaId");
//							String startTime = (String) filter.get("startTime") ;
//							String endTime = (String) filter.get("endTime") ;
//							Long recipeTypeId = (Long) filter.get("recipeTypeId") ;
//							Long foodId = (Long) filter.get("foodId") ;
//
							//去重
							Map<String, Object> filter = new HashMap<String, Object>();
							filter.put("areaId", areaId);
							filter.put("foodId", recipeFood.getId());
							filter.put("recipeTypeId",Long.valueOf(recipeConfig.getValue()));
							filter.put("startTime", CookbookUtils.dateToStr(recipeDate, CookbookUtils.DEFINE_YYYY_MM_DD));
							filter.put("endTime", CookbookUtils.dateToStr(recipeDate, CookbookUtils.DEFINE_YYYY_MM_DD));

							List<Recipe> recipes = recipeService.selectRecipeListByCondition(filter);
                            if(recipes != null && recipes.size() > 0) {
                            	continue;
							}

							Recipe recipe = new Recipe();
                            recipe.setAreaId(areaId);
                            recipe.setRecipeDate(recipeDate);
                            recipe.setRecipeTypeName(recipeTypeName);
                            recipe.setFoodId(recipeFood.getId());
                            recipe.setRecipeTypeId(Long.valueOf(recipeConfig.getValue()));

                            recipeList.add(recipe);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
				}
			}
		}

		if(!CollectionUtils.isEmpty(recipeList)){
			recipeService.insertRecipeByRecipeList(recipeList);
			recipeService.insertRecipeJSON(recipeDateList,areaId);
		}

		return StatusResponse.success();
	}

	@ApiOperation(value = "导出模板",httpMethod = "POST")
	@RequestMapping(value = "/export_excel_recipe_food")
	@ResponseBody
	public StatusResponse exportExcelRecipeFood(@RequestHeader(TICKET) String ticket,String startDate) {
		AreaDTO area = ssoCallService.getAreaDTO(ticket);
		String areaId = area.getId();

		List<Map<String,Object>> weekRecipeList = getAWeekRecipeList(startDate,areaId);
		List<String> weekDays = getWeekDays(startDate);
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFSheet sheet = workbook.createSheet("健康食谱");
		createRowIndex0(workbook,sheet);
		createRowIndex1(workbook,sheet,weekDays);
		createRowIndexI(workbook,sheet, weekRecipeList);
		mergedCell(sheet);

		sheet.setDefaultColumnWidth(17);
		sheet.setDefaultRowHeight((short) (4 * 256));
		sheet.setHorizontallyCenter(true);
		sheet.setVerticallyCenter(true);

		sheet.setColumnWidth(0,10 * 256);
		sheet.setColumnWidth(1,20 * 256);
		sheet.setColumnWidth(2,20 * 256);
		sheet.setColumnWidth(3,20 * 256);
		sheet.setColumnWidth(4,20 * 256);
		sheet.setColumnWidth(5,20 * 256);
		sheet.setColumnWidth(6,20 * 256);
		sheet.setColumnWidth(7,20 * 256);


		String uploadedResult = null;
		try {
			String uploadCourseName = area.getName() + "(" + weekDays.get(0) + "~" + weekDays.get(weekDays.size() - 1) + ")";
			String fileName = UUID.randomUUID().toString();
			String uploadPath = "teach/file/recipe_export_excel/" + DateTime.now().toString("yyyy-MM") + "/" + uploadCourseName + ".xlsx";

			File outputFile = File.createTempFile(fileName,"xlsx");
			FileOutputStream fileOutputStream = new FileOutputStream(outputFile);

			workbook.write(fileOutputStream);
			String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputFile);
			uploadedResult = IMG_SERVICE_PREFIX + relativePath;
			outputFile.deleteOnExit();
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return StatusResponse.success(uploadedResult);
	}

	private static void mergedCell(XSSFSheet sheet) {
		Row row1 = sheet.getRow(1);
		int lastCellNum = row1.getLastCellNum();
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, lastCellNum - 1));
	}

	private void createRowIndexI(Workbook workbook ,XSSFSheet sheet, List<Map<String, Object>> weekRecipeList) {

		for(int i = 1; i <= weekRecipeList.size(); i++){

			Map<String,Object> recipe = weekRecipeList.get(i - 1);
			List<List<Map<String, Object>>> weekFoodList = (List<List<Map<String, Object>>>)recipe.get("recipeDayFoods");
			String recipeTypeName = String.valueOf(recipe.get("recipeTypeName"));

			Row rowI = sheet.createRow(sheet.getLastRowNum() + 1);
			Cell rowICell0 = rowI.createCell(0);
			rowICell0.setCellValue(recipeTypeName);

			CellStyle style = workbook.createCellStyle();
			PoiUtils.setupCellTableStyle(style);

			style.setWrapText(true);

			rowICell0.setCellStyle(style);

		    for(int j = 1; j <= weekFoodList.size(); j++){
				List<Map<String,Object>> dayFoods = weekFoodList.get(j - 1);
				Cell rowICellJ = rowI.createCell(j);
				StringBuffer foodFormat = new StringBuffer();
				for(Map<String,Object> food : dayFoods){
					String foodName = String.valueOf(food.get("food_name"));
					foodFormat.append(foodName).append(",");
				}
				rowICellJ.setCellValue(StringUtils.removeEnd(foodFormat.toString(),","));
				rowICellJ.setCellStyle(style);
			}
        }
	}

	private void createRowIndex1(Workbook workbook, XSSFSheet sheet ,List<String> weekDays) {

		CellStyle style = workbook.createCellStyle();

		PoiUtils.setupCellTableStyle(style);

		style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);


		Row row1 = sheet.createRow(1);
		Cell row1Cell0 = row1.createCell(0);
		row1Cell0.setCellValue("餐次");
		row1Cell0.setCellStyle(style);



		for(int i = 0 ; i < weekDays.size(); i++){
			String day = weekDays.get(i);
			DateTime dayDateTime = DateTime.parse(day);
			int week = dayDateTime.getDayOfWeek();
			String weekCN = getWeekCN(week);
			String dayFormat = dayDateTime.toString("MM-dd");
			String dateFormat = weekCN + "/" + dayFormat;

			Cell row1CellI = row1.createCell(i + 1);
			row1CellI.setCellValue(dateFormat);
			row1CellI.setCellStyle(style);
		}
	}

	private static void createRowIndex0(Workbook workbook , XSSFSheet sheet) {

		CellStyle style = workbook.createCellStyle();
		style.setAlignment(HorizontalAlignment.CENTER);
		style.setVerticalAlignment(VerticalAlignment.CENTER);

		Font font = workbook.createFont();
		font.setFontHeightInPoints((short) 14);
//		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setBold(true);
		font.setFontName("宋体");
		font.setColor(IndexedColors.LIGHT_BLUE.getIndex());
		style.setFont(font);

		Row row0 = sheet.createRow(0);
		Cell row0Cell0 = row0.createCell(0);
		row0Cell0.setCellValue("健康食谱");

		row0Cell0.setCellStyle(style);

	}

	private static List<String> getWeekDays(String monday){
		int days = 7;
		List<String> weekDays = new ArrayList<>();
		weekDays.add(monday);
		for (int i = 1; i < days ; i++){
			DateTime nextDay = DateTime.parse(monday).plusDays(i);
			weekDays.add(nextDay.toString("yyyy-MM-dd"));
		}
		return weekDays;
	}

	private static String getWeekCN(int week){
		switch (week){
			case 1: return "周一";
			case 2: return "周二";
			case 3: return "周三";
			case 4: return "周四";
			case 5: return "周五";
			case 6: return "周六";
			case 7: return "周日";
		}
		return "周一";
	}

}
